<!-- @tce
代码说明： 系统管理下传感器管理的页面
创建时间：2024.9.9       开发者：lizhicheng
使用项目：zhongguanghe   代码版本：V1.0 -->

<template>
  <div>
    <el-card>
      <!-- 筛选和上传区域 -->
      <el-row :gutter="20" type="flex" justify="start" align="middle">
        <el-col :span="7">
          <el-select v-model="selectedSensorModel" placeholder="选择传感器型号">
            <el-option
                v-for="model in sensorModels"
                :key="model.value"
                :label="model.label"
                :value="model.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="12" style="display: flex; align-items: center">
          <el-button id="filter-button" type="primary" @click="filterData"
          >筛选</el-button
          >
          <el-button id="reset-button" type="default" @click="resetFilter"
          >重置</el-button
          >
<!--          action="http://localhost:8080/sensors/uploadExcel"-->
          <el-upload
              action="http://10.78.34.117:8888/sensors/uploadExcel"
              name="file"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              style="margin-left: 10px"
          >
            <el-button type="primary" style="width: 8vw;">上传Excel文件</el-button>
          </el-upload>
          <el-button
              type="primary"
              style="margin-left: 10px ; width: 8vw;"
              @click="openAddSensorDialog"
          >新增传感器</el-button
          >
        </el-col>
      </el-row>

      <!-- 新增传感器信息对话框 -->
      <el-dialog title="新增传感器信息" v-model="addDialogVisible" width="35%">
        <el-form :model="newSensor">
          <el-form-item label="传感器型号:">
            <el-input v-model="newSensor.sensModel"></el-input>
          </el-form-item>
          <el-form-item label="设备名称:">
            <el-input v-model="newSensor.sensName"></el-input>
          </el-form-item>
          <el-form-item label="设备代码:">
            <el-input v-model="newSensor.sensCode"></el-input>
          </el-form-item>
          <el-form-item label="数量:" >
            <el-input v-model="newSensor.counts"></el-input>
          </el-form-item>
          <el-form-item label="制造厂家:">
            <el-input v-model="newSensor.manufacture"></el-input>
          </el-form-item>
          <el-form-item label="监测内容:">
            <el-input v-model="newSensor.sensDesc"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSensor">保存</el-button>
        </template>
      </el-dialog>

      <!-- 修改传感器信息对话框 -->
      <el-dialog title="修改传感器信息" v-model="editDialogVisible" width="35%">
        <el-form :model="editSensor">
          <el-form-item label="传感器型号:">
            <el-input v-model="editSensor.sensModel"></el-input>
          </el-form-item>
          <el-form-item label="设备名称:">
            <el-input v-model="editSensor.sensName"></el-input>
          </el-form-item>
          <el-form-item label="设备代码:">
            <el-input v-model="editSensor.sensCode" disabled></el-input>
            <!-- 禁用 -->
          </el-form-item>
          <el-form-item label="数量:" >
            <el-input v-model="editSensor.counts"></el-input>
          </el-form-item>
          <el-form-item label="制造厂家:">
            <el-input v-model="editSensor.manufacture"></el-input>
          </el-form-item>
          <el-form-item label="监测内容:">
            <el-input v-model="editSensor.sensDesc"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </template>
      </el-dialog>

      <!-- 列表区 -->
      <div style="height: 60vh">
        <el-skeleton :loading="loading" animated>
          <el-table
              :data="paginatedData"
              border
              height="100%"
              style="width: 100%; margin-top: 20px"
          >
            <!-- 新添加的序号列 -->
            <el-table-column label="序号" min-width="30">
              <template #default="scope">
                {{
                  scope.$index + 1 + (searchForm.current - 1) * searchForm.size
                }}
              </template>
            </el-table-column>
            <el-table-column prop="sensModel" label="传感器型号" min-width="150" />
            <el-table-column prop="sensName" label="设备名称" min-width="50"/>
            <el-table-column prop="sensCode" label="设备代码" min-width="70"/>
            <el-table-column prop="counts" label="数量" min-width="30"/>
            <el-table-column prop="manufacture" label="制造厂家" />
            <el-table-column prop="sensDesc" label="监测内容" />
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="primary" @click="editRow(row)">修改</el-button>
                <el-button
                    id="delete-button"  type="default"
                    @click="deleteRow(row)"
                    style="margin-left: 10px;background-color: #f56c6c;"
                >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>

      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
              :total="total"
              :current-page.sync="searchForm.current"
              :total-pages="totalPages"
              @update:currentPage="handlePageChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>


<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import smApi from "@/api/sensorManagement"; // 替换为你的 API
import Pagination from "@/components/Table/Pagination";

// const debug = (index, currentPage, pageSize) => {
//     console.log('index:', index);
//     console.log('currentPage:', currentPage);
//     console.log('pageSize:', pageSize);
//     return index + 1 + (currentPage - 1) * pageSize;
// };

// 编辑对话框是否可见
const editDialogVisible = ref(false);

// 新增对话框是否可见
const addDialogVisible = ref(false);

// 当前正在编辑的传感器数据
const editSensor = reactive({
  sensModel: "",
  sensName: "",
  sensCode: "",
  counts: "",
  manufacture: "",
  sensDesc: "",
});

// 新增传感器的表单数据
const newSensor = reactive({
  sensModel: "",
  sensName: "",
  sensCode: "",
  counts: "",
  manufacture: "",
  sensDesc: "",
});

// 打开新增传感器对话框
const openAddSensorDialog = () => {
  addDialogVisible.value = true;
};

// 触发编辑传感器
const editRow = (row) => {
  console.log("点击了编辑按钮");
  console.log("选中的行数据:", row);

  // 将选中的传感器信息复制到 editSensor 中
  Object.assign(editSensor, row);

  // 显示对话框
  editDialogVisible.value = true;
  console.log("editSensor 内容:", editSensor);
  console.log("对话框是否显示:", editDialogVisible.value);
};

// 修改传感器信息
const confirmEdit = async () => {
  try {
    console.log("编辑传感器:", editSensor); // 检查 editSensor 的内容
    const res = await smApi.updateSensor(editSensor.sensCode, editSensor); // 这里确保 sensCode 是 editSensor.sensCode
    if (res.data.status) {
      ElMessage.success("传感器信息修改成功");
      editDialogVisible.value = false;
      getFaultDiagnosesTableData(); // 刷新表格数据
      fetchSensorModels(); // 刷新传感器类型数据
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
};

// 新增传感器的操作
const addSensor = async () => {
  try {
    const res = await smApi.addSensors(newSensor);
    if (res.data.status) {
      ElMessage.success("传感器新增成功");
      await fetchSensorModels(); // 重新获取传感器型号数据
      getFaultDiagnosesTableData();
      resetNewSensorForm();
      addDialogVisible.value = false; // 关闭对话框
    } else {
      ElMessage.error("新增失败");
    }
  } catch (error) {
    ElMessage.error("新增请求失败");
  }
};

// 重置新增表单
const resetNewSensorForm = () => {
  newSensor.sensModel = "";
  newSensor.sensName = "";
  newSensor.sensCode = "";
  newSensor.counts = "";
  newSensor.manufacture = "";
  newSensor.sensDesc = "";
};

// 传感器型号下拉框数据
const sensorModels = ref([]); // 使用 ref 存储动态传感器型号数据
const selectedSensorModel = ref(""); // 当前选中的传感器型号

// 获取传感器型号
const fetchSensorModels = async () => {
  try {
    const res = await smApi.getSensorModels(); // 替换为你的 API 接口
    console.log("Fetched sensor models1:", res.data.data);
    if (res.data.status) {
      // 使用原始数据中的每个字符串作为 label 和 value
      sensorModels.value = res.data.data.map((model) => ({
        label: model, // 使用字符串作为 label 和 value
        value: model,
      }));
      console.log("Fetched sensor models2:", sensorModels.value); // 检查数据
    } else {
      ElMessage.error("获取传感器型号失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
};

// 页面加载时获取传感器型号
onMounted(() => {
  fetchSensorModels();
  getFaultDiagnosesTableData();
});

// 其他已有代码
const allTableData = ref([]); // 接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length); // 总记录条数
const totalPages = ref(1); // 总页数

watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
});

const handlePageChange = (page) => {
  searchForm.current = page;
};

const searchForm = reactive({
  current: 1,
  size: 10,
});

// 获取传感器数据
const getFaultDiagnosesTableData = async () => {
  const res = await smApi.getSensors();
  if (res.data.status) {
    allTableData.value = res.data.data;
  } else {
    ElMessage.error("获取后端数据失败");
  }
};

// 计算当前页数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

// 筛选数据
const filterData = () => {
  tableData.value = allTableData.value.filter((item) => {
    return selectedSensorModel.value
        ? item.sensModel === selectedSensorModel.value
        : true;
  });
};

// 重置筛选
const resetFilter = () => {
  selectedSensorModel.value = "";
  tableData.value = [...allTableData.value];
};

// 上传文件处理
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success("Excel 文件上传并导入成功");
    getFaultDiagnosesTableData(); // 刷新表格数据
    fetchSensorModels(); // 更新传感器型号下拉框
  } else {
    ElMessage.error("Excel 文件上传成功，但导入失败");
  }
};

const handleUploadError = () => {
  ElMessage.error("Excel 文件上传失败");
};

// 删除传感器
const deleteRow = async (row) => {
  ElMessageBox.confirm(`确定删除 ${row.sensCode} 吗？`, "警告", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        const res = await smApi.deleteSensor(row.sensCode);
        if (res.data.status) {
          ElMessage.success("删除成功");
          getFaultDiagnosesTableData(); // 刷新表格数据
          fetchSensorModels(); // 更新传感器型号下拉框
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};

// 加载loading页面
const loading = ref(true);
watch(
    () => paginatedData.value,
    (newValue) => {
      loading.value = !(newValue && newValue.length > 0);
    },
    { immediate: true }
);
</script>


<style scoped lang="scss">
/* 上传按钮样式 */
.el-button {
  @include button-style;
}

/* 弹框样式 */
.el-alert {
  margin-top: 20px;
}

/* 重置-删除按钮 */

#delete-button,
#reset-button {
  background-color: $color-reset-button;

  &:hover {
    background-color: #babfd3;
  }
}

/* card背景、边框 */
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}

/* 数据表背景 */
:deep(.el-table) {
  color: $color-font-table; // 字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;

  // 鼠标悬停时的行样式
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}
//card下边框设置
:deep(.el-card__body) {
  padding: 0 0 20px;
}

//输入框背景颜色设置
:deep(.el-select__wrapper) {
  background-color: transparent;
}
:deep(.el-select__placeholder) {
  color:white;
}

//对话框设置
:deep(.el-dialog__title) {
  color: white;
}
:deep(.el-form-item__label) {
  color: white;
  text-align: right;
  width:120px;
}
:deep(.el-input__inner) {
  color: white;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: transparent;

}

:deep(.el-input__wrapper ) {
  background-color: transparent;
}
:deep(.el-dialog) {

  background: #14255f;


}
</style>
